'use client'

import FilterCarousel from '@/components/filter-carousel'
import { trpc } from '@/lib/trpc'
import { useRouter } from 'next/navigation'
import React, { Suspense } from 'react'
import { ErrorBoundary } from 'react-error-boundary'

interface CategoriesSectionProps {
    categoryId?: string
}

export function CategoriesSectionSuspense({ categoryId }: CategoriesSectionProps) {
    const [categories] = trpc.categories.getMany.useSuspenseQuery()

    const data = categories.map((item) => ({
        value: item.id,
        label: item.name,
    }))

    const router = useRouter()

    const onSelect = (value: string | null) => {
        const url = new URL(window.location.href)

        if (value) {
            url.searchParams.set('categoryId', value)
        } else {
            url.searchParams.delete('categoryId')
        }
        router.push(url.toString())
    }

    return (
        <div>
            <FilterCarousel data={data} value={categoryId} onSelect={onSelect} />
        </div>
    )
}

export default function CategoriesSection({ categoryId }: CategoriesSectionProps) {
    return (
        <Suspense fallback={<FilterCarousel isLoading data={[]} />}>
            <ErrorBoundary fallbackRender={({ error }) => <p>error:{error.message}</p>}>
                <CategoriesSectionSuspense categoryId={categoryId} />
            </ErrorBoundary>
        </Suspense>
    )
}